package com.tanhua.server.util;

import com.tanhua.domain.db.User;
import io.jsonwebtoken.*;
import org.springframework.context.annotation.Bean;

public class JwtUtils {
    public static String createToken(User user, String secret) {
        return Jwts.builder()
                .claim("id", user.getId())
                .claim("mobile", user.getMobile())
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();

    }

    public static Boolean isValidToken(String secret, String token) {
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static User parseToken(String secret, String token) {
        Jws<Claims> jws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
        Claims claims = jws.getBody();
        Object id = claims.get("id");
        String mobile = (String) claims.get("mobile");
        User user = new User();
        user.setId(Long.parseLong(id.toString()));
        user.setMobile(mobile);
        return user;
    }
}
